let socket = null;
let currentRoom = 'general';
let isConnected = false;

// 连接WebSocket
function connect() {
  const token = document.getElementById('token').value;

  try {
    // 动态获取当前协议和主机，修复跨域问题
    const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
    const host = window.location.host;

    // 添加跨域支持
    const socketOptions = {
      path: '/ws',
      auth: token ? { token } : {},
      transports: ['websocket', 'polling'],
      upgrade: true,
      rememberUpgrade: true,
      forceNew: true,
      timeout: 20000,
      // HTTP环境下的配置
      secure: false,
      // 添加跨域支持
      withCredentials: true,
      extraHeaders: {
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Credentials': 'true',
      },
    };

    console.log('WebSocket连接选项:', socketOptions);
    socket = io(socketOptions);

    socket.on('connect', () => {
      isConnected = true;
      updateConnectionStatus(true);
      addMessage('系统', 'WebSocket连接成功！', 'success');

      // 自动加入默认房间
      joinRoom();
    });

    socket.on('disconnect', () => {
      isConnected = false;
      updateConnectionStatus(false);
      addMessage('系统', 'WebSocket连接断开', 'error');
    });

    socket.on('authenticated', (data) => {
      addMessage('系统', `认证成功: ${data.user.username}`, 'success');
    });

    socket.on('room-joined', (data) => {
      addMessage('系统', data.message, 'info');
    });

    socket.on('room-left', (data) => {
      addMessage('系统', data.message, 'info');
    });

    socket.on('new-message', (message) => {
      addMessage(message.payload.sender, message.payload.text, 'message');
    });

    socket.on('private-message', (message) => {
      addMessage(
        `私信: ${message.payload.sender}`,
        message.payload.text,
        'private',
      );
    });

    socket.on('user-status-update', (message) => {
      const status = message.payload.status;
      const userId = message.payload.userId;
      addMessage('系统', `用户 ${userId} 状态更新: ${status}`, 'status');
    });

    socket.on('error', (error) => {
      addMessage('系统', `错误: ${error.message}`, 'error');
    });
  } catch (error) {
    addMessage('系统', `连接失败: ${error.message}`, 'error');
  }
}

// 断开连接
function disconnect() {
  if (socket) {
    socket.disconnect();
    socket = null;
    isConnected = false;
    updateConnectionStatus(false);
    addMessage('系统', '已断开连接', 'info');
  }
}

// 加入房间
function joinRoom() {
  if (!socket || !isConnected) {
    addMessage('系统', '请先连接WebSocket服务', 'error');
    return;
  }

  const room = document.getElementById('roomSelect').value;
  socket.emit('join-room', room);
  currentRoom = room;
  addMessage('系统', `正在加入房间: ${room}`, 'info');
}

// 发送消息
function sendMessage() {
  if (!socket || !isConnected) {
    addMessage('系统', '请先连接WebSocket服务', 'error');
    return;
  }

  const message = document.getElementById('messageInput').value.trim();
  if (!message) {
    addMessage('系统', '请输入消息内容', 'error');
    return;
  }

  socket.emit('send-message', {
    room: currentRoom,
    message: message,
  });

  addMessage('我', message, 'own');
  document.getElementById('messageInput').value = '';
}

// 切换房间
function switchRoom(room) {
  if (!socket || !isConnected) {
    addMessage('系统', '请先连接WebSocket服务', 'error');
    return;
  }

  // 离开当前房间
  socket.emit('leave-room', currentRoom);

  // 加入新房间
  socket.emit('join-room', room);
  currentRoom = room;

  // 更新UI
  document.querySelectorAll('.room-btn').forEach((btn) => {
    btn.classList.remove('active');
  });
  event.target.classList.add('active');

  addMessage('系统', `已切换到房间: ${room}`, 'info');
}

// 更新连接状态
function updateConnectionStatus(connected) {
  const statusEl = document.getElementById('connectionStatus');
  if (connected) {
    statusEl.className = 'status connected';
    statusEl.textContent = '已连接';
  } else {
    statusEl.className = 'status disconnected';
    statusEl.textContent = '未连接';
  }
}

// 添加消息
function addMessage(sender, content, type = 'message') {
  const messagesEl = document.getElementById('messages');
  const messageEl = document.createElement('div');
  messageEl.className = 'message';

  const time = new Date().toLocaleTimeString();
  const senderClass = type === 'own' ? 'sender own' : 'sender';

  messageEl.innerHTML = `
        <div class="time">${time}</div>
        <div class="content">
            <span class="${senderClass}">${sender}:</span> ${content}
        </div>
    `;

  messagesEl.appendChild(messageEl);
  messagesEl.scrollTop = messagesEl.scrollHeight;
}

// 页面加载完成后的初始化
document.addEventListener('DOMContentLoaded', function () {
  addMessage('系统', '页面加载完成，点击"连接"按钮开始使用', 'info');

  // 绑定按钮事件
  document.getElementById('connectBtn').addEventListener('click', connect);
  document
    .getElementById('disconnectBtn')
    .addEventListener('click', disconnect);
  document
    .getElementById('sendMessageBtn')
    .addEventListener('click', sendMessage);
  document.getElementById('joinRoomBtn').addEventListener('click', joinRoom);

  // 绑定房间切换事件
  document.querySelectorAll('.room-btn').forEach((btn) => {
    btn.addEventListener('click', function () {
      const room = this.getAttribute('data-room');
      switchRoom(room);
    });
  });

  // 回车发送消息
  document
    .getElementById('messageInput')
    .addEventListener('keypress', function (e) {
      if (e.key === 'Enter' && !e.shiftKey) {
        e.preventDefault();
        sendMessage();
      }
    });
});
